package com.wkbb.basic.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.feign.DoorFeignService;
import com.wkbb.basic.feign.TcCloudFeignService;
import com.wkbb.basic.mapper.*;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.*;
import com.wkbb.basic.thread.BacisDeleteAddressBookKeyTask;
import com.wkbb.basic.utils.ExcelErrorTipUtil;
import com.wkbb.basic.utils.ExcelFieldUtil;
import com.wkbb.basic.utils.FillEmptyHeadImgUtil;
import com.wkbb.basic.vo.EmployeeEditInfoVo;
import com.wkbb.basic.vo.TeacherManageVo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.CommonConstant;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.*;
import com.wkbb.common.enums.*;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author dengjingyuan
 */
@Service
@Slf4j
public class TeacherManageServiceImpl extends BaseServiceImpl<Employee> implements TeacherManageService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ClassInfoService classInfoService;

    @Autowired
    private UserOpenService userOpenService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private TcCloudFeignService tcCloudFeignService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private ImportLogService importLogService;

    @Autowired
    @Lazy
    private XmppService xmppService;

    @Autowired
    private TeacherCourseMapper teacherCourseMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Autowired
    private YouTuService youTuService;

    @Autowired
    private DoorFeignService doorFeignService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private NationalityService nationalityService;

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;


    @Autowired
    public void setMapper(EmployeeMapper employeeMapper) {
        super.setMapper(employeeMapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insert(EmployeeInfoDto employeeInfoDto, String createBy) {
        String headImg = FillEmptyHeadImgUtil.checkHeadImg(employeeInfoDto.getSex(), RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getHeadImgUrl(), false);
        if (!StringUtil.isNullOrBlank(headImg)) {
            log.info("默认头像地址：" + headImg);
            employeeInfoDto.setHeadImgUrl(headImg);
        }

        Map<String,Object> result = new HashMap<String,Object>();
        User user = userMapper.getByPrimaryKey(employeeInfoDto.getUserId());
        Long userId;
        Employee employee=new Employee();

        //先获取userType
        BeanUtils.copyProperties(employeeInfoDto, employee);

        //拿到userType
        employee = employeeService.fillPosition(employee);

        BeanUtils.copyProperties(employee, employeeInfoDto);

        if (null != user) {
            userId = user.getId();
            //插入老师表
            employee = employeeService.insertEmployee(employeeInfoDto, userId, createBy);

            //有用户信息,修改roleType  JSON权限
            Object roleType = userService.updateRoleTypeJson(user.getRoleType(), null, Short.parseShort("" + RoleTypeEnum.TEACHER.getValue()), null, employeeInfoDto.getOrgId(),user.getId());
            user.setRoleType(roleType);
            userMapper.update(user);
            //更新redis
            userService.updateUserInfo(employeeInfoDto.getOrgId(), userId);
        } else {
            Object roleType = userService.updateRoleTypeJson(null, null, Short.parseShort("" + RoleTypeEnum.TEACHER.getValue()), null, employeeInfoDto.getOrgId(),null);
            user = new User();
            BeanUtils.copyProperties(employeeInfoDto, user);
            user.setRoleType(roleType);
            user.setStatus(true);
            user.setUserCode(UuIdUtil.getUserCodeByUUId());
            userService.insert(employeeInfoDto.getOrgId(), user, RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getSex(), employeeInfoDto.getUserType(),employeeInfoDto.getSmartWxUserId(),employeeInfoDto.getIsSmartSubscribe());
            userId = user.getId();

            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(employeeInfoDto, userInfo);
            if (!StringUtils.isEmpty(employeeInfoDto.getHeadImgUrl())) {
                userInfo.setHeadImgMd5(userService.getImageMD5(employeeInfoDto.getHeadImgUrl()));
            }
            userInfo.setUserId(userId);
            userInfoMapper.insert(userInfo);

            employee = employeeService.insertEmployee(employeeInfoDto, userId, createBy);
        }

        result.put("employee",employee);
        result.put("user",user);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertTeacher(EmployeeInfoDto employeeInfoDto, String createBy,Boolean isSendToXmppOrSendToDoor,Boolean isClearAddressBook) {
        Map<String,Object> result = insert(employeeInfoDto,createBy);
        User user =  result.get("user") == null? null : (User) result.get("user");
        Employee employee= result.get("employee")== null? null : (Employee) result.get("employee");

        if(employee ==null|| user == null) {
            return null;
        }

        //添加老师权限
        SysRoleUser sysRoleUser = new SysRoleUser();
        sysRoleUser.setOrgId(employeeInfoDto.getOrgId());
        sysRoleUser.setRoleId(3L);
        sysRoleUser.setUserId(user.getId());
        sysRoleUser.setCreateBy(createBy);
        sysRoleUser.setUpdateBy(createBy);
        sysRoleUserMapper.insert(sysRoleUser);

        /*if(isSendToXmppOrSendToDoor){
            //xmpp推送更新用户通行权限
            ThreadPoolUtil.addPoolTask(new SynUserAccessXmppTask(doorFeignService, employee.getOrgId(), user.getId(), RoleTypeEnum.TEACHER,xmppService,null,null,null,true,false,true,false,(short)RoleTypeEnum.TEACHER.getValue(),null));
        }*/

       /* //新增老师,更新学校老师通讯录
        try {
            //tcCloudFeignService.getCheckImAccount(user.getId(), null, user.getHeadImgUrl(),employeeInfoDto.getOrgId(),Short.valueOf(RoleTypeEnum.TEACHER.getValue()+""),employee.getUserType());

            Integer type = null;
            if (employee.getUserType().intValue() == UserTypeEnum.TEACHER.getValue()) {
                type = AddressListEnum.TEACHER.getValue();

            } else {
                type = AddressListEnum.PRINCIPAL.getValue();

                //单个园长,进入所有的群
                ThreadPoolUtil.addTask( new ImSaveAutoGroupUserMasterOneTask(classInfoService,employeeInfoDto.getOrgId(), employee.getUserType(), employee,user));

            }

            if(isClearAddressBook) {
                ThreadPoolUtil.addPoolTask(new BacisDeleteAddressBookKeyTask(user.getId(), type, employee.getOrgId(), userOpenService));
            }
        } catch (Exception e) {
            log.error("**********老師新增(沒有任課),刪除學校所有教职工通讯录缓存异常**********");
        }*/
        return user.getId();
    }

    @Override
    public void updateTeacher(EmployeeInfoDto employeeInfoDto, String updateBy) throws Exception {
        updateTeacher(employeeInfoDto, updateBy, false, false);
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> update(EmployeeInfoDto employeeInfoDto, String updateBy, boolean isBack, boolean updateAccount) throws Exception {
        //当头像为空,默认设置头像.否则走正常变更
        boolean flag=false;
        if(!StringUtil.isEmptyIgnoreBlank(employeeInfoDto.getHeadImgUrl())){
            flag=true;
        }
        String headImg = FillEmptyHeadImgUtil.checkHeadImg(employeeInfoDto.getSex(), RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getHeadImgUrl(), flag);
        if (!StringUtil.isNullOrBlank(headImg)) {
            log.info("默认头像地址：" + headImg);
            employeeInfoDto.setHeadImgUrl(headImg);
        }

        Employee employee = new Employee();
        Map<String,Object> result = new HashMap<String,Object>();
        //先获取userType
        BeanUtils.copyProperties(employeeInfoDto, employee);

        //拿到userType
        employee = employeeService.fillPosition(employee);

        BeanUtils.copyProperties(employee, employeeInfoDto);

        result.put("employee",employee);

        //后台修改才做校验，小程序不会做身份的更换操作
        //判断园长是否是负责人,是则提示“该园长为学校负责人不可直接变更为老师，请先更换负责人！”
//        if(isBack) {
//            Organization organization = organizationMapper.getByPrimaryKey(employeeInfoDto.getOrgId());
//            if (null != organization) {
//                //如果设置为非园长岗位,并且是负责人,则提示不能直接降级
//                if (employeeInfoDto.getUserType() == null || employeeInfoDto.getUserType().intValue() != UserTypeEnum.MASTER.getValue()) {
//                    if (null != organization.getMasterId() && organization.getMasterId().longValue() == employeeInfoDto.getUserId().longValue()) {
//                        result.put("resultDTO",new ResultDTO(ErrorCode.MASTER_CANT_DOWNGRADE));
//                        return  result;
//                    }
//                }
//            }
//        }

        BeanUtils.copyProperties(employeeInfoDto, employee);
        if (!StringUtil.isNullOrBlank(employeeInfoDto.getPassword())) {
            employee.setPassword(MD5Util.getMD5Code(employeeInfoDto.getPassword()));
        } else {
            employee.setPassword(null);
        }
        employee.setUpdateBy(updateBy);

        employeeService.fillPosition(employee);
        employeeInfoDto.setOriUserType(employee.getOriUserType());
        employeeInfoDto.setUserType(employee.getUserType());

        if (isBack) {
            employee.setUpdateAccount(updateAccount);//是否修改账号密码
            employeeMapper.updateBack(employee);
        } else {
            employeeMapper.update(employee);
        }

        User user = userMapper.getByPrimaryKey(employeeInfoDto.getUserId());
        result.put("user",user);
        BeanUtils.copyProperties(employeeInfoDto, user);
        //employee的ID将user的ID覆盖了，employee的userId才是user的ID
        user.setId(employeeInfoDto.getUserId());
        Object roleType = userService.updateRoleTypeJson(user.getRoleType(), employeeInfoDto.getOriUserType(), Short.parseShort("" + RoleTypeEnum.TEACHER.getValue()), employeeInfoDto.getOldOrgId(), employeeInfoDto.getOrgId(),user.getId());
        user.setRoleType(roleType);
        user.setMobile(employeeInfoDto.getMobile());
        user.setHeadImgUrl(employeeInfoDto.getHeadImgUrl());
        userService.update(employeeInfoDto.getOrgId(), user, RoleTypeEnum.TEACHER.getValue(), isBack,employeeInfoDto.getSmartWxUserId(),employeeInfoDto.getIsSmartSubscribe());

        Map<String, Object> params = new HashMap<>(1);
        params.put("userId", employeeInfoDto.getUserId());
        UserInfo userInfo = userInfoMapper.getByMapParams(params);
        BeanUtils.copyProperties(employeeInfoDto, userInfo);
        if (!StringUtils.isEmpty(employeeInfoDto.getHeadImgUrl())) {
            userInfo.setHeadImgMd5(userService.getImageMD5(employeeInfoDto.getHeadImgUrl()));
        }
        userInfoService.update(userInfo, isBack);

        //更新相应班主任信息
        classInfoService.updateMaster(user, updateBy);


        return result;
    }

    @Override
    public ResultDTO updateTeacher(EmployeeInfoDto employeeInfoDto, String updateBy, boolean isBack, boolean updateAccount) throws Exception {

        log.info("***进入老师信息修改 userId:{}***", employeeInfoDto.getUserId());
        Map<String,Object> result = update(employeeInfoDto,updateBy,isBack,updateAccount);
        User user =  result.get("user") == null? null : (User) result.get("user");
        ResultDTO resultDTO = result.get("resultDTO")== null? null : (ResultDTO) result.get("resultDTO");
        Employee employee= result.get("employee")== null? null : (Employee) result.get("employee");

        if(resultDTO !=null){
            return resultDTO;
        }
        if(employee ==null|| user == null) {
            return new ResultDTO();
        }

        //xmpp推送更新用户通行权限
        //ThreadPoolUtil.addPoolTask(new SynUserAccessXmppTask(doorFeignService, employee.getOrgId(), employee.getUserId(), RoleTypeEnum.TEACHER, xmppService, null, null, null, true, false, true, false,(short)RoleTypeEnum.TEACHER.getValue(),null));

        //修改老师,更新学校老师通讯录
        try {

            log.info("**********老師修改(沒有任課),刪除學校所有教职工通讯录缓存开始**********");
            Integer type = null;
            /*if (employee.getUserType().intValue() == UserTypeEnum.TEACHER.getValue()) {
                type = AddressListEnum.TEACHER.getValue();

                //修改老师或园长IM用户头像
                log.info("**********修改老师IM用户头像**********");
                tcCloudFeignService.updateImUserInfo(employeeInfoDto.getOrgId(),employeeInfoDto.getUserId(),(short)RoleTypeEnum.TEACHER.getValue(),UserTypeEnum.TEACHER.getValue().shortValue(),user.getHeadImgUrl());
            } else {
                type = AddressListEnum.PRINCIPAL.getValue();

                //修改老师或园长IM用户头像
                log.info("**********修改园长IM用户头像**********");
                tcCloudFeignService.updateImUserInfo(employeeInfoDto.getOrgId(),employeeInfoDto.getUserId(),(short)RoleTypeEnum.TEACHER.getValue(),UserTypeEnum.MASTER.getValue().shortValue(),user.getHeadImgUrl());
            }*/

            ThreadPoolUtil.addPoolTask(new BacisDeleteAddressBookKeyTask(employeeInfoDto.getUserId(), type, employee.getOrgId(),userOpenService));//清园长通讯录
            log.info("**********老師修改(沒有任課),刪除學校所有教职工通讯录缓存结束**********");

            //后台修改才做校验，小程序不会做身份的更换操作
            //老师变更园长，园长变更老师异步处理，注意:这段代码需要放在这个位置,否则头像,昵称的缓存没有改变，取出的昵称会有问题
//            if (isBack) {
//                changeUserType(employeeInfoDto, employee);
//            }
        } catch (Exception e) {
            log.error("**********老師修改(沒有任課),刪除學校所有教职工通讯录缓存异常**********",e);
            return new ResultDTO(false);
        }
        return new ResultDTO();
    }

    @Override
    public void changeUserType(EmployeeInfoDto employeeInfoDto, Employee employee) throws Exception {
        List<NickNameDto> nickNameList = new ArrayList<NickNameDto>();
        NickNameDto nickNameDto = new NickNameDto();
        nickNameDto.setUserId(employeeInfoDto.getUserId());
        nickNameDto.setOrgId(employeeInfoDto.getOrgId());
        nickNameDto.setRoleType(RoleTypeEnum.TEACHER.getValue());
        nickNameDto.setUserType(employeeInfoDto.getUserType().intValue());
        nickNameList.add(nickNameDto);

        nickNameList = userOpenService.getNickName(nickNameList);

        log.info("---------------------------老师升级为园长,园长降级为老师之前拼接昵称值:{}---------------------------",JSONObject.toJSONString(nickNameList));

        //老师角色变更,修改IM群角色
       // tcCloudFeignService.updateAllGroupUserInfo(employeeInfoDto.getUserId(), employeeInfoDto.getOrgId(), RoleTypeEnum.TEACHER.getValue(), employeeInfoDto.getOriUserType(), employeeInfoDto.getUserType(), nickNameList.get(0).getNickName());

        //IM相关开始---------------------------老师升级为园长,园长降级为老师---------------------------
        /*log.info("IM相关开始---------------------------老师升级为园长,园长降级为老师---------------------------");
        //-----------老师升级为园长,需要根据岗位来判断?需要新增一个oriUserType来判断
        Long orgId = employeeInfoDto.getOrgId();
        Long userId = employeeInfoDto.getUserId();
        Short oriUserType = employeeInfoDto.getOriUserType();
        Short userType = employeeInfoDto.getUserType();
        log.info("----老师升级为园长,园长降级为老师----orgId={},userId={},oriUserType={},userType={}",orgId,userId,oriUserType,userType);
        if(oriUserType.shortValue() == UserTypeEnum.TEACHER.getValue()
                && userType.shortValue()== UserTypeEnum.MASTER.getValue()){
            //老师升级为园长(老师和园长身份二选一,升级为园长说明原来只是某些班的管理员,现在需要加入到每个班级群成为管理员)
            //先查询出已经加入的班级群
            //再查询全校班级,排除掉已经加入过的班级,加入到其他班级群中
            log.info("----老师升级为园长开始---");
            classInfoService.saveAutoGroupUserMaster(orgId,UserTypeEnum.MASTER.getValue().shortValue(),null,null,null);
            log.info("----老师升级为园长结束---");
        }else if(oriUserType.shortValue() == UserTypeEnum.MASTER.getValue()
                && userType.shortValue()== UserTypeEnum.TEACHER.getValue()){

            //判断是否有任课班级，和任班主任班级,是：退包含非任课，非班主任的班级群，否：退出全部班级群
            log.info("----园长降级为老师开始---");
            masterDowngrade(orgId,userId);
            log.info("----园长降级为老师结束---");
        }
        log.info("IM相关结束---------------------------老师升级为园长,园长降级为老师---------------------------");
        //IM相关结束---------------------------老师升级为园长,园长降级为老师---------------------------
*/    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMobile(EmployeeInfoDto employeeInfoDto) throws Exception {
        Employee employee = new Employee();
        employee.setMobile(employeeInfoDto.getMobile());
        employee.setUserId(employeeInfoDto.getUserId());
        employeeMapper.update(employee);

        User user = userMapper.getByPrimaryKey(employeeInfoDto.getUserId());
        //employee的ID将user的ID覆盖了，employee的userId才是user的ID
        user.setId(employeeInfoDto.getUserId());
        Object roleType = userService.updateRoleTypeJson(user.getRoleType(), employeeInfoDto.getOriUserType(), Short.parseShort("" + RoleTypeEnum.TEACHER.getValue()), employeeInfoDto.getOldOrgId(), employeeInfoDto.getOrgId(),user.getId());
        user.setRoleType(roleType);
        user.setMobile(employeeInfoDto.getMobile());
        userService.update(employeeInfoDto.getOrgId(), user, RoleTypeEnum.TEACHER.getValue(), false,employeeInfoDto.getSmartWxUserId(),employeeInfoDto.getIsSmartSubscribe());
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> delete(List<Long> ids, String deleteBy) throws Exception {
        if (ids == null || ids.isEmpty()) {
            return null;
        }

        Map<String,Object> result = new HashMap<String,Object>();
        List<Employee> employeeList = new ArrayList<Employee>();

        for (Long id : ids) {
            if (id == null || id == 0) {
                continue;
            }

            Employee employee = employeeMapper.getByPrimaryKey(id);
            if (employee == null) {
                continue;
            }

//            ClassInfoDto classInfoDto = classInfoService.getClassInfoByMasterId(employee.getOrgId(), employee.getUserId());
//            if (classInfoDto != null) {
//                result.put("resultDTO",new ResultDTO(ErrorCode.TEACHER_IS_MASTER));
//                return result;
//            }

            //IM相关开始---------------------------批量删除老师---------------------------
            //在此处判断是否要退群
            //判断是园长还是老师，如果是老师,直接退所有任课的班级群;
            //删除园长: 判断该园长是否为负责人，若是则提示不可删除，需转让负责人之后才可以删除，
            //若不是负责人还要判断是否有在班级任课或担任班主任，若有则转换成班级群的管理员，若无任课也不是负责人，删除即退出所有群
            //园长
//            log.info("IM相关开始---------------------------批量删除老师---------------------------");
//            Long orgId = employee.getOrgId();
//            Long masterId = employee.getUserId();
//            log.info("-----orgId={},masterId={},userType={}----",orgId,masterId,employee.getUserType().intValue());
//            if(employee.getUserType().intValue() == UserTypeEnum.MASTER.getValue()){
//                log.info("----------开始删除园长----------");
//                //此处逻辑是:
//                //1.先判断是否是负责人,如果是则提示:提示不能删除，需要先更换负责人(IM转让群主，走变更负责人流程);
//                //先查询学校信息
//                Organization organization = organizationMapper.getByPrimaryKey(orgId);
//                if(null!=organization.getMasterId() && organization.getMasterId().longValue() == masterId.longValue()){
//                    //事务回滚,全部都不删除?还是只有园长不删除?
////                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                    result.put("resultDTO",new ResultDTO(ErrorCode.MASTER_CANT_DELETE));
//                    return result;
//                }else {
//                   // masterOutGroup(orgId,masterId);
//                }
//                log.info("----------删除园长结束----------");
//            }else if(employee.getUserType().intValue() == UserTypeEnum.TEACHER.getValue()){
//                log.info("----------开始删除老师----------");
//                //退出所有班级群,包括任课班级和担任班主任的班级
//               // teacherOutGroup(orgId,masterId);
//                log.info("----------删除老师结束----------");
//                //之前做的逻辑是班主任不能删除,因此此处不需要判断退出所任班主任的班级群
//            }
            log.info("IM相关结束---------------------------批量删除老师---------------------------");
            //IM相关结束---------------------------批量删除老师---------------------------

            //删除任课信息
            classInfoService.deleteTeacherCourseByMasterId(employee.getUserId());
            userService.deleteUserInfo(employee.getOrgId(), employee.getUserId(), RoleTypeEnum.TEACHER.getValue());

            employee.setUpdateBy(deleteBy);
            employee.setStatus(false);
            employeeMapper.update(employee);

            employeeList.add(employee);

            //清除缓存
            //userService.deleteRedisWkbbBasicUserBack(employee.getUserId(), employee.getOrgId());
        }

        result.put("userIdList",employeeList);
        return result;
    }

    @Override
    public ResultDTO deleteTeacher(List<Long> ids, String deleteBy) throws Exception {
        Map<String,Object> result = delete(ids,deleteBy);
        return new ResultDTO();
//        ResultDTO resultDTO = result.get("resultDTO")== null? null : (ResultDTO) result.get("resultDTO");
//        List<Employee> employeeList= result.get("userIdList")== null? null : (List<Employee>) result.get("userIdList");

//        if(resultDTO !=null){
//            return resultDTO;
//        }
//        if(employeeList == null|| employeeList.isEmpty()) {
//            return new ResultDTO();
//        }
//
//        employeeList.forEach(
//                employee->{
//                    //删除家长对应删除IM账号缓存
//                  /*  ResultDTO<Object> imUserRedis = tcCloudFeignService.getImUserRedis(employee.getUserId(), employee.getOrgId(), (short) RoleTypeEnum.TEACHER.getValue(),employee.getUserType().shortValue());
//                    if (ResultDTO.checkSuccess(imUserRedis) && null != imUserRedis.getData()) {
//                        log.info("----------清除该用户IM缓存----------userId:{}",employee.getUserId());
//                        redisTemplateUtil.delete(imUserRedis.getData().toString());
//                    }
//
//                    //xmpp推送更新用户通行权限
//                    ThreadPoolUtil.addPoolTask(new SynUserAccessXmppTask(doorFeignService, employee.getOrgId(), employee.getUserId(), RoleTypeEnum.TEACHER, 1,xmppService,null,null,null,true,false,true,false,(short)RoleTypeEnum.TEACHER.getValue(),null));
//*/
//                    //删除老师,更新学校老师通讯录
//                    try {
//                        log.info("**********老師新增(沒有任課),刪除學校所有教职工通讯录缓存开始**********");
//                        ThreadPoolUtil.addPoolTask(new BacisDeleteAddressBookKeyTask(employee.getUserId(), AddressListEnum.TEACHER.getValue(), employee.getOrgId(),userOpenService));
//
//                        ThreadPoolUtil.addPoolTask(new BacisDeleteAddressBookKeyTask(employee.getUserId(), AddressListEnum.PRINCIPAL.getValue(), employee.getOrgId(),userOpenService));
//                        log.info("**********老師新增(沒有任課),刪除學校所有教职工通讯录缓存结束**********");
//                    } catch (Exception e) {
//                        log.error("**********老師新增(沒有任課),刪除學校所有教职工通讯录缓存异常**********");
//                    }
//                }
//        );

//        return new ResultDTO();
    }

    @Override
    public void deleteUserFaceByOrgId(Long userId, Long orgId){

        try{

            log.info("----------检测当前用户删除的学校----------orgId:{},userId:{},user:{}",orgId,userId);

            List<YoutuFace> youtuFaceList = youTuService.selectFaceByuserCode(userId, orgId);

            log.info("----------检测当前用户需要删除的人脸----------orgId:{},userId:{},youtuFaceList:{}", orgId, userId, youtuFaceList);
            if (CollectionUtils.isNotEmpty(youtuFaceList)) {

                for (YoutuFace youtuFace : youtuFaceList) {

                    youTuService.deleteFace( youtuFace.getPersonId(), orgId);
                }

                log.info("----------删除当前用户所有人脸结束----------orgId:{},userId:{}", orgId, userId);
            }

        }catch (Exception e){
            log.error("----------删除当前用户所有人脸异常----------e",e);
        }
    }

    /**
     * 园长降级为老师,只需要退出不任课的班级群,不需要删除IM账号
     * 判断是否有在班级任课或担任班主任，若有退出非(任课和担任班主任)的班级群，若无任课也不是班主任，即退出所有班级群
     */
    private void masterDowngrade(Long orgId,Long userId){
        Set<Long> outGroupClassIds = getOutGroupClassIds(orgId,userId);

        Integer roleType = RoleTypeEnum.TEACHER.getValue();
        Integer userType = UserTypeEnum.TEACHER.getValue();

        outGroup(outGroupClassIds,orgId,userId,roleType,userType,false);
    }

    /**
     * 删除园长,需要退出全部班级群,并且需要删除IM账号
     * 判断是否有在班级任课或担任班主任，若有退出非(任课和担任班主任)的班级群，若无任课也不是班主任，即退出所有班级群
     */
    private void masterOutGroup(Long orgId,Long userId){
        Set<Long> outGroupClassIds = getOrgAllClassIds(orgId);

        Integer roleType = RoleTypeEnum.TEACHER.getValue();
        Integer userType = UserTypeEnum.MASTER.getValue();
        //退群
        //这里默认先不进行IM账号删除,不能在循环里面进行Im账号删除,会有问题,会提前把ImUser的status变为0
        outGroup(outGroupClassIds,orgId,userId,roleType,userType,false);

        //注意:在这里单独update,不能在循环里面进行imAccount账号删除,因为后面没有办法查询
        userOpenService.deleteImAccount(orgId,userId,roleType,userType);
    }

    /**
     * 删除老师,需要退出全部任课的班级群,并且需要删除IM账号
     * 判断是否有在班级任课或担任班主任，若有退出非(任课和担任班主任)的班级群
     */
    private void teacherOutGroup(Long orgId,Long userId){
        Set<Long> outGroupClassIds = getTeacherCourseClassIds(orgId,userId);

        Integer roleType = RoleTypeEnum.TEACHER.getValue();
        Integer userType = UserTypeEnum.TEACHER.getValue();
        //退群
        //这里默认先不进行IM账号删除,不能在循环里面进行Im账号删除,会有问题,会提前把ImUser的status变为0
        outGroup(outGroupClassIds,orgId,userId,roleType,userType,false);

        //注意:在这里单独update,不能在循环里面进行imAccount账号删除,因为后面没有办法查询
        userOpenService.deleteImAccount(orgId,userId,roleType,userType);
    }

    private ResultDTO outGroup(Set<Long> outGroupClassIds,Long orgId,Long userId,Integer roleType,Integer userType,Boolean isDeleteImAccount){
        for(Long classId:outGroupClassIds){
            ResultDTO resultDto = userOpenService.operateGroupUser(ImOperGroupTypeEnum.OUT_GROUP.getValue(), orgId, classId, userId, null, roleType, userType, isDeleteImAccount);
            log.info("---masterOutGroup---operateGroupUser执行结果:{}",JSONObject.toJSONString(resultDto));
            if(!resultDto.isSuccess()){
                return resultDto;
            }
        }
        return new ResultDTO();
    }

    /**
     * 获取要退群的班级列表
     * @param orgId
     * @param userId
     * @return
     */
    private Set<Long> getOutGroupClassIds(Long orgId,Long userId){
        //查询出任课全部班级,true or false
        log.info("--masterOutGroup--参数--orgId={},userId={}",orgId,userId);
        //查询出全校所有班级
        Set<Long> outGroupClassIds = getOrgAllClassIds(orgId);

        Set<Long> classIds = getTeacherCourseClassIds(orgId,userId);
        //全部班级-不需要退出的班级=需要退出的班级群
        if(CollectionUtils.isNotEmpty(classIds)){
            outGroupClassIds.removeAll(classIds);
        }
        log.info("---masterOutGroup---需要退出的班级群=全部班级-不需要退出的班级--outGroupClassIds={}",JSONObject.toJSONString(outGroupClassIds));
        return outGroupClassIds;
    }

    /**
     * 获取任课的和任班主任的班级
     * @param orgId
     * @param userId
     * @return
     */
    private Set<Long> getTeacherCourseClassIds(Long orgId,Long userId){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("orgId",orgId);
        paramMap.put("masterId",userId);
        paramMap.put("status",1);
        List<TeacherCourse> teacherCourseList = teacherCourseMapper.getListByMapParams(paramMap);
        log.info("--getTeacherCourseClassIds--查询出任课全部班级,teacherCourseList={}",JSONObject.toJSONString(teacherCourseList));
        //记录不需要退出的班级ID集合
        Set<Long> classIds = new HashSet<>();
        if(CollectionUtils.isNotEmpty(teacherCourseList)){
            for(TeacherCourse teacherCourse : teacherCourseList){
                classIds.add(teacherCourse.getClassId());
            }
        }
        //查询出任班主任的班级,参数orgId,masterId
        ClassInfo classInfo = classInfoMapper.getByMapParams(paramMap);
        if (null != classInfo) {
            classIds.add(classInfo.getId());
        }
        log.info("--getTeacherCourseClassIds--查询出任课全部班级+出任班主任的班级,classIds={}",classIds);
        return classIds;
    }

    /**
     * 获取此学校全部班级
     * @param orgId
     */
    private Set<Long> getOrgAllClassIds(Long orgId){
        //查询出任课全部班级,true or false
        //查询出全校所有班级
        Set<Long> outGroupClassIds = new HashSet<>();
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("orgId",orgId);
        paramMap.put("status",1);
        List<ClassInfo> classInfoList = classInfoMapper.getListByMapParams(paramMap);
        for(ClassInfo oriClassInfo:classInfoList){
            outGroupClassIds.add(oriClassInfo.getId());
        }
        log.info("--getOrgAllClassIds--查询出学校全部班级,outGroupClassIds={}",JSONObject.toJSONString(outGroupClassIds));
        return outGroupClassIds;
    }

    @Override
    public EmployeeEditInfoVo getTeacherInfoById(Long id, UserDto userDto) {
        return employeeMapper.getEmployeeInfoById(id);
    }

    @Override
    public PageInfo<EmployeeInfoDto> getTeacherInfoPageList(Map<String, Object> params, Integer pageNo, Integer pageSize) {

        if (pageNo == null || pageSize == null) {
            return null;
        }
        Page<EmployeeInfoDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<EmployeeInfoDto> pageInfo = new PageInfo<>(
                employeeMapper.getEmployeeInfoPageList(params));
        pageInfo.setTotal(page.getTotal());

        return pageInfo;
    }

    @Override
    public PageInfo<TeacherManageVo> getTeacherManageList(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageSize == null) {
            return null;
        }
        Page<TeacherManageVo> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<TeacherManageVo> pageInfo = new PageInfo<>(
                employeeMapper.getTeacherManagerPageList(params));

        //加上是否已经上传人脸判断
        /*List<TeacherManageVo> list = pageInfo.getList();
        if(CollectionUtils.isNotEmpty(list)){
            //因为orgId是必须传的参数,因此获取AccountId可以提取出来
            Long accountId = userOpenService.getAccountIdByOrgId(list.get(0).getOrgId());
            for(TeacherManageVo teacherManageVo : list){
                teacherManageVo.setAccountId(accountId);
                // Boolean hasUploadFace = youTuService.checkHasUploadFace(teacherManageVo.getOrgId(),teacherManageVo.getUserId());
                // teacherManageVo.setHasUploadFace(hasUploadFace);
            }
        }*/

        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

    @Override
    public List<Object[]> exportTeacherExcel(Map<String, Object> params,Long orgId) {

        //查询需要导出的数据
        List<TeacherManageVo> teacherManageListExcel = employeeMapper.getTeacherManagerPageList(params);
        OrganizationDto organizationDto = organizationMapper.getOrgInfoById(orgId);

        if(null==organizationDto){
            return null;
        }
        try {
            if (CollectionUtils.isNotEmpty(teacherManageListExcel)) {
                List<Object[]> data = new ArrayList<>(teacherManageListExcel.size());
                //返回教职工数据
                teacherManageListExcel.forEach(e -> {
                    Object[] d = new Object[8];
                    int i = 0;
                    d[i++] =organizationDto.getName()  == null ? "-" : organizationDto.getName();
                    d[i++] = e.getName() == null ? "-" : e.getName();
                    d[i++] = e.getPositionName() == null ? "-" : e.getPositionName();
                    d[i++] = e.getMobile() == null ? "-" : e.getMobile();
                    d[i++] = e.getJobNo() == null ? "-" : e.getJobNo();
                    d[i++] = e.getCardNo() == null ? "-" : e.getCardNo();
                    d[i++] = e.getHasUploadFace() == null ? "-" : e.getHasUploadFace()==true? "已上传" : "未上传";
                    d[i++] = StringUtil.isEmptyIgnoreBlank(e.getCreateTime())? "-" : e.getCreateTime();
                    data.add(d);
                });
                return data;
            }
        }catch (Exception e) {
            log.error("填充老师报表excel数据异常,msg:{}", e);
        }
        return null;
    }

    @Override
    public Map<String, Object> getTeacherCount(Map<String, Object> params) {
        return employeeMapper.getTeacherCount(params);
    }


    @Override
    public List<TeacherManageVo> getAllTeacherManageList(Map<String, Object> params) {
        return employeeMapper.getTeacherManagerList(params);
    }

    @Override
    public PageInfo<EmployeeInfoDto> getEmployeeInfoPageByClassId(Map<String, Object> params, Integer pageNo, Integer pageSize) {
        if (pageNo == null || pageSize == null) {
            return null;
        }
        Page<EmployeeInfoDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<EmployeeInfoDto> pageInfo = new PageInfo<>(getEmployeeInfoListByClassId(params));
        pageInfo.setTotal(page.getTotal());

        return pageInfo;
    }

    /**
     * 根据组织ID获取职员列表
     *
     * @param params 参数（学校ID,班级ID）
     * @return 教师列表
     * @throws Exception 抛出异常
     */
    @Override
    public List<EmployeeInfoDto> getEmployeeInfoList(Map<String, Object> params) throws Exception {
        return employeeMapper.getEmployeeInfoList(params);
    }

    @Override
    public List<EmployeeInfoDto> getEmployeeInfoListByClassId(Map<String, Object> params) {
        return employeeMapper.getEmployeeInfoListByClassId(params);
    }

    /**
     * 查询班级教师列表(包含班主任)
     */
    @Override
    public List<EmployeeInfoDto> getEmployeeInfoByClass(Map<String, Object> params) {
        return employeeMapper.getEmployeeInfoClass(params);
    }

    /**
     * 园长获取班级教师列表(包含园长)
     *
     * @param params 参数（学校ID,班级ID）
     * @return 教师列表
     */
    @Override
    public List<EmployeeInfoDto> getEmployeeListBySchoolMaster(Map<String, Object> params) {

        //查询班级教师列表(包含班主任)
        List<EmployeeInfoDto> employeeInfoList = employeeMapper.getEmployeeInfoClass(params);

        //查询园长
        List<EmployeeInfoDto> masterEmployeeInfoList = employeeMapper.getSchoolMasterInfo(params);

        //合并数据
        List<EmployeeInfoDto> list = new ArrayList<>(masterEmployeeInfoList);
        if (masterEmployeeInfoList.size() > 0) {
            for (EmployeeInfoDto masterEmployeeInfo : masterEmployeeInfoList) {
                for (EmployeeInfoDto employeeInfoDto : employeeInfoList) {
                    if (masterEmployeeInfo.getUserId().equals(employeeInfoDto.getUserId())) {
                        list.remove(employeeInfoDto);
                    }
                }
            }
        }

        //加入班主任数据
        employeeInfoList.addAll(list);

        return employeeInfoList;
    }

    /**
     * 获取学校教师列表(包含园长)，排除非当前班级的班主任
     *
     * @param orgId   学校ID
     * @param classId 班级ID
     * @return 全校老师列表(包含园长)，排除非本班班主任
     */
    @Override
    public List<TeacherManageVo> getTeacherListExcludeOtherMaster(Long orgId, Long classId) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("orgId", orgId);

        //园长获取全校教师列表(包含园长)
        List<TeacherManageVo> teacherManageList = getAllTeacherManageList(params);

        if (teacherManageList == null || teacherManageList.isEmpty()) {
            return null;
        }

        //查找全校有班主任的班级信息
        List<ClassInfo> classInfoList = classInfoService.getClassMasterListByOrgId(orgId);
        //从老师中筛选掉除本班班主任以外的班主任信息
        List<TeacherManageVo> tempList = new ArrayList<>(teacherManageList);
        for (ClassInfo classInfo : classInfoList) {
            //本班班主任不筛选
            if (classId != null && classInfo.getId() == classId.longValue()) {
                continue;
            }

            //筛选其他班主任
            for (TeacherManageVo teacherManageVo : tempList) {
                if (teacherManageVo.getUserId() == classInfo.getMasterId().longValue()) {
                    teacherManageList.remove(teacherManageVo);
                }
            }
        }
        return teacherManageList;
    }

    @Override
    public List<EmployeeInfoDto> getAllEmployeeList(Long orgId) {
        return employeeMapper.getAllEmployeeList(orgId);
    }

    //propagation = Propagation.SUPPORTS, 如果存在一个事务，支持当前事务。如果没有事务，则非事务的执行
    //propagation = NOT_SUPPORTED, 以非事务方式运行，如果当前存在事务，则把当前事务挂起
    //propagation = NEVER：以非事务方式运行，如果当前存在事务，则抛出异常
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, rollbackFor = Exception.class)
    public ResultDTO<Map<String,Object>> saveData(UserDto userDto, Long orgId, List<Object[]> data, String flag,Integer currentRow,Boolean isClearAddressBook) throws Exception {
        return importNewOrgTeacherData(userDto, orgId, data,currentRow,isClearAddressBook);
    }

    /**
     {0=学校名称, 1=教师姓名*, 2=性别*, 3=岗位*, 4=手机号*, 5=出生日期, 6=教工号, 7=入职日期, 8=民族, 9=考勤卡号}
     */
    private ResultDTO<Map<String,Object>> importNewOrgTeacherData(UserDto userDto, Long selectedOrgId, List<Object[]> data,Integer currentRow,Boolean isClearAddressBook) throws Exception {
        if (null == selectedOrgId || CollectionUtils.isEmpty(data)) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }
        //定义一个Map,用于存储每条数据,什么原因而失败
        Map<String,Object> returnMap = new HashMap();
        List<TeacherManageVo> importFailList = new ArrayList();
        List<TeacherManageVo> importOkList = new ArrayList<>();
        Long newOrgId = null;

        Organization oriOrganization = organizationMapper.getByPrimaryKey(selectedOrgId);
        //默认是幼儿园
        Integer orgType = OrganizationTypeEnum.KINDERGARTEN.getValue();
        if(null!=oriOrganization) {
            orgType = oriOrganization.getOrgType();
        }
        List<Position> positionList = positionService.getPositionList(orgType);
        List<NationalityDto> nationalityList = nationalityService.getNationalityList();
        //{0=学校名称*, 1=教师姓名*, 2=性别*, 3=岗位*, 4=手机号*, 5=出生日期, 6=教工号, 7=入职日期, 8=民族, 9=考勤卡号}
        for (Object[] objects : data) {
            TeacherManageVo teacherManageVo = changeToEntityForNew(objects);
            //阶段1,先检查所有字段的合法性,不合法直接跳至下一条数据,再去验证系统中数据有效性,通过则导入
            //判断学校名称(1、非空 2、学校名称和当前PC端选择的学校名称一致，可正常导入)
            String orgName = objects[0].toString();
            if(StringUtils.isEmpty(orgName)){
                ExcelErrorTipUtil.notNullValid(ExcelFieldUtil.ORG_NAME,teacherManageVo,importFailList);
                continue;
            }
            Organization organization = organizationService.getOrgByName(orgType, orgName);
            if (null!=organization && organization.getId().longValue()==selectedOrgId.longValue()) {
                newOrgId = organization.getId();
            } else {
                ExcelErrorTipUtil.validField(ErrorCode.SELECTED_ORG_WRONG,teacherManageVo,importFailList);
                continue;
            }
            //教师姓名(1、非空 2、姓名长度在8位数以内（包含位），无特殊字符或空格 3、教师姓名可以重复（前提是不是同一个手机号）)
            String name = objects[1].toString();
            if (ExcelErrorTipUtil.checkUserNameField(name, ExcelFieldUtil.TEACHER_NAME, teacherManageVo, importFailList, true)) {
                continue;
            }
            //性别(1、非空 2、性别：男或女)
            String sex = objects[2].toString();
            if(ExcelErrorTipUtil.checkSexField(sex,teacherManageVo,importFailList)) {
                continue;
            }
            //岗位(1、非空 2、与系统给的17个岗位一致，无特殊符号)
            String positionName = objects[3].toString();
            if (ExcelErrorTipUtil.checkPositionField(positionName, positionList, teacherManageVo, importFailList)) {
                continue;
            }
            //教师手机号
            String mobile = objects[4].toString();
            if (ExcelErrorTipUtil.checkMobileField(mobile, ExcelFieldUtil.MOBILE, teacherManageVo, importFailList, true)){
                continue;
            }
            //出生日期是可空的
            Date birthDate = null;
            Object birthDateObj = objects[5];
            if(ExcelErrorTipUtil.checkDateField(birthDateObj,teacherManageVo,importFailList,ExcelFieldUtil.BIRTH_DATE)){
                continue;
            }else{
                birthDate = ExcelErrorTipUtil.formatObjectDate(birthDateObj);
            }

            //教工号
            //1、非必填
            //2、教工号长度不超过20位数（包含20位）
            //3、教工号无中文，无特殊符号，
            //4、教工号在本校内唯一，可正常导入
            String jobNo = objects[6].toString();
            if(StringUtils.isNotEmpty(jobNo)){
                Integer maxLength = 20;
                if(jobNo.trim().length()>maxLength){
                    String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.FIELD_LENGTH_ERROR,ExcelFieldUtil.JOB_NO,maxLength);
                    ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                    continue;
                }else if(VerifyUtil.checkCharacters(jobNo) || VerifyUtil.checkZhCharacters(jobNo)){
                    String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.FIELD_CHAR_ZH_ERROR,ExcelFieldUtil.JOB_NO);
                    ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                    continue;
                }
                //教工号要在学校唯一
                Map<String,Object> paramMap = new HashMap();
                paramMap.put("orgId",newOrgId);
                paramMap.put("jobNo",jobNo);
                List<Employee> employeeList = employeeMapper.getListByMapParams(paramMap);
                if(CollectionUtils.isNotEmpty(employeeList)){
                    String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.NO_EXIST_ERROR,ExcelFieldUtil.JOB_NO,ExcelFieldUtil.JOB_NO);
                    ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                    continue;
                }
            }
            //入职日期是可空的
            Date enterDate = null;
            Object enterDateObj = objects[7];
            if(ExcelErrorTipUtil.checkDateField(enterDateObj,teacherManageVo,importFailList,ExcelFieldUtil.ENTER_DATE)){
                continue;
            }else{
                enterDate = ExcelErrorTipUtil.formatObjectDate(enterDateObj);
            }

            //民族是可空的
            String nationality = objects[8].toString();
            if(ExcelErrorTipUtil.checkNationalityField(nationality,nationalityList,teacherManageVo,importFailList)){
                continue;
            }

            //考勤卡号
            //  1、非必填
            //  2、考勤卡号在表内是唯一的，并且在系统中也是唯一的
            //  3、考勤卡号位数不超过10位数字（包含10位）
            //  4、考勤卡号是数字或英文，没有特殊符号，多张卡号用半角逗号隔开，
            //  5、考勤卡号能是一张
            //   学生考勤卡，家长考勤卡，老师考勤卡系统内唯一(包括三张表,employee,student,family)
            String cardNo = objects[9].toString();
            if(StringUtil.isNotEmpty(cardNo)){
                String[] cardNos = cardNo.split(",");
                if(cardNos.length == 1) {
                    Integer maxLength = 10;
                    if(cardNos[0].length()>maxLength){
                        String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.FIELD_LENGTH_ERROR,ExcelFieldUtil.CARD_NO,maxLength);
                        ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                        continue;
                    }else if(VerifyUtil.checkCharacters(cardNos[0]) || VerifyUtil.checkZhCharacters(cardNos[0])){
                        String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.FIELD_CHAR_ZH_ERROR,ExcelFieldUtil.CARD_NO);
                        ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                        continue;
                    }
                }else if(cardNos.length>1){
                    ExcelErrorTipUtil.validField(ErrorCode.CARD_COUNT_ERROR,teacherManageVo,importFailList);
                    continue;
                }else{
                    String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.CHAR_SPLIT_ERROR,ExcelFieldUtil.CARD_NO);
                    ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                    continue;
                }
                //学校唯一
                if(userService.checkCardNoUnique(cardNo,newOrgId)){
                    String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.NO_EXIST_ERROR,ExcelFieldUtil.CARD_NO,ExcelFieldUtil.CARD_NO);
                    ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                    continue;
                }
            }

            UserInfoDto userInfoDto = userService.checkMobileUnique(newOrgId,mobile,RoleTypeEnum.TEACHER.getValue());
            //已经存在此手机号码,不导入数据
            if (null != userInfoDto && !StringUtils.isEmpty(userInfoDto.getMobile())) {
                String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.USER_EXIST_ERROR,ExcelFieldUtil.TEACHER);
                ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                continue;
            }

            if (null != newOrgId) {
                //在此处封装对象
                EmployeeInfoDto employeeInfoDto = new EmployeeInfoDto();
                employeeInfoDto.setOrgId(newOrgId);
                employeeInfoDto.setName(name);
                employeeInfoDto.setMobile(mobile);
                employeeInfoDto.setSex(sex);
                employeeInfoDto.setBirthDate(birthDate);
                employeeInfoDto.setPositionId(teacherManageVo.getPositionId());
                employeeInfoDto.setPositionName(positionName);
                employeeInfoDto.setCardNo(cardNo);
                employeeInfoDto.setJobNo(jobNo);
                employeeInfoDto.setEnterDate(enterDate);
                employeeInfoDto.setNationality(nationality);

                User user = userService.checkUserMobile(mobile);
                //判断身份,如果不是学生
                if (null == user) {
                    insertTeacher(employeeInfoDto,userDto.getName(),false,isClearAddressBook);
                    //addTeacher(userDto,newOrgId,employeeInfoDto);
                    ExcelErrorTipUtil.validField(ErrorCode.IMPORT_SUCCESS,teacherManageVo,importOkList);
                } else {
                    //已经存在一条mobile,接下来判断roleType,如果是学生直接导入失败
                    Boolean flag = ExcelErrorTipUtil.checkRoleExist(user.getRoleType());
                    //如果已经存在,应该怎么样提示?
                    if(!flag){
                        employeeInfoDto.setUserId(user.getId());
                        insertTeacher(employeeInfoDto,userDto.getName(),false,isClearAddressBook);
                        //updateTeacher(userDto,newOrgId,employeeInfoDto,user.getId());
                        ExcelErrorTipUtil.validField(ErrorCode.IMPORT_SUCCESS,teacherManageVo,importOkList);
                    }else {
                        String fieldErrorMsg = ExcelErrorTipUtil.fieldErrorTip(ErrorCode.USER_EXIST_ERROR,ExcelFieldUtil.TEACHER);
                        ExcelErrorTipUtil.validField(fieldErrorMsg,teacherManageVo,importFailList);
                        continue;
                    }
                }
            }
            currentRow++;
        }

        saveImportLog(userDto,newOrgId,importOkList,importFailList);

        returnMap.put("success",importOkList);
        returnMap.put("fail",importFailList);
        return new ResultDTO(returnMap);
    }

    //save到数据库
    private void saveImportLog(UserDto userDto,Long newOrgId,List<TeacherManageVo> importOkList,List<TeacherManageVo> importFailList){
        if(CollectionUtils.isNotEmpty(importOkList)) {
            importLogService.addImportLog(userDto, newOrgId, Short.valueOf("1"), true, JSONObject.toJSONString(importOkList));
        }
        if(CollectionUtils.isNotEmpty(importFailList)){
            importLogService.addImportLog(userDto, newOrgId, Short.valueOf("1"), false, JSONObject.toJSONString(importFailList));
        }
    }

    /**
     *  只显示学校名称,老师姓名,手机号,失败原因
     * @param objects
     * @return
     */
    private TeacherManageVo changeToEntityForNew(Object[] objects) {
        TeacherManageVo teacherManageVo = new TeacherManageVo();
        teacherManageVo.setOrgName(objects[0].toString());
        teacherManageVo.setName(objects[1].toString());
        teacherManageVo.setSex(objects[2].toString());
        teacherManageVo.setPositionName(objects[3].toString());
        teacherManageVo.setMobile(objects[4].toString());
        return teacherManageVo;
    }

    //先判断是否同一个老师（不能同一个人重复导入）
    private Boolean checkEmployee(Long orgId, String mobile) {
        Boolean isExist = false;
        Map<String, Object> employeeParams = new HashMap<String, Object>();
        employeeParams.put("orgId", orgId);
        employeeParams.put("mobile", mobile);
        Employee oriEmployee = employeeMapper.getByMapParams(employeeParams);
        if (null != oriEmployee) {
            isExist = true;
        }
        return isExist;
    }

    private void addTeacher(UserDto userDto, Long newOrgId,EmployeeInfoDto employeeInfoDto) {
        String mobile = employeeInfoDto.getMobile();
        String sex = employeeInfoDto.getSex();
        String name = employeeInfoDto.getName();
        Date birthDate = employeeInfoDto.getBirthDate();
        String nationality = employeeInfoDto.getNationality();

        boolean isExist = checkEmployee(newOrgId, mobile);
        if (isExist) {
            return;
        }
        //如果性别为空,则性别默认为男性
        if (StringUtils.isEmpty(sex)) {
            sex = "男";
        }
        User user = new User();
        user.setName(name);
        //先按照一个单个角色来导入
        //[{"orgId": 1, "roleTypes": [{"roleType": 1, "roleTypeName": "教师"}]}]
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orgId", newOrgId);

        JSONArray roleTypesArray = new JSONArray();
        JSONObject roleTypesObject = new JSONObject();
        roleTypesObject.put("roleType", RoleTypeEnum.TEACHER.getValue());
        roleTypesObject.put("roleTypeName", RoleTypeEnum.TEACHER.getDesc());
        roleTypesArray.add(roleTypesObject);

        jsonObject.put("roleTypes", roleTypesArray);
        jsonArray.add(jsonObject);
        user.setRoleType(jsonArray);
        user.setMobile(mobile);
        user.setStatus(true);
        user.setUserCode(UuIdUtil.getUserCodeByUUId());
        String headImgUrl = FillEmptyHeadImgUtil.checkHeadImg(sex, RoleTypeEnum.TEACHER.getValue(), "", false);
        if (StringUtil.isNotEmpty(headImgUrl)) {
            user.setHeadImgUrl(headImgUrl);
        }
        userMapper.insert(user);

        //得到insert之后的新的userId
        Long newUserId = user.getId();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(newUserId);
        userInfo.setSex(sex);
        userInfo.setBirthDate(birthDate);
        userInfo.setNationality(nationality);
        if (StringUtil.isNotEmpty(user.getHeadImgUrl())) {
            userInfo.setHeadImgMd5(userService.getImageMD5(user.getHeadImgUrl()));
        }
        userInfoMapper.insert(userInfo);

        insertEmployee(userDto, newOrgId, newUserId,employeeInfoDto);
    }

    private void updateTeacher(UserDto userDto, Long orgId, EmployeeInfoDto employeeInfoDto, Long userId) throws Exception {
        String mobile = employeeInfoDto.getMobile();
        String name = employeeInfoDto.getName();

        boolean isExist = checkEmployee(orgId, mobile);
        if (isExist) {
            return;
        }

        //修改USER表roleType
        User user = userMapper.getByPrimaryKey(userId);
        Object roleType = userService.updateRoleTypeJson(user.getRoleType(), null, Short.parseShort("" + RoleTypeEnum.TEACHER.getValue()), null, orgId,user.getId());
        user.setName(name);
        user.setRoleType(roleType);
        userService.update(orgId, user, RoleTypeEnum.TEACHER.getValue(), false,null,false);

        insertEmployee(userDto, orgId, userId,employeeInfoDto);
    }

    private void insertEmployee(UserDto userDto, Long orgId, Long userId,EmployeeInfoDto employeeInfoDto) {
        String mobile = employeeInfoDto.getMobile();
        String positionName = employeeInfoDto.getPositionName();
        Long positionId = employeeInfoDto.getPositionId();
        String cardNo = employeeInfoDto.getCardNo();
        String jobNo = employeeInfoDto.getJobNo();
        Date enterDate = employeeInfoDto.getEnterDate();

        Employee employee = new Employee();
        employee.setOrgId(orgId);
        employee.setUserId(userId);
        //根据岗位来判断
        //2.0岗位总共有6个,园长,老师,校车司机,生活护理,普通职工,其他
        //31-园长,32-副园长,33-主任,34-财务,35-保健医生,36-级组长,37-主班,38-副班,39-兴趣班老师,40-保育员,41-保安,42-厨房,43-后勤,44-实习老师,45-营养师,46-司机,47-其他
        if (Arrays.asList(CommonConstant.MASTER_NAME_LIST).contains(positionName)) {
            employee.setUserType(UserTypeEnum.MASTER.getValue().shortValue());
        }else{
            employee.setUserType(UserTypeEnum.TEACHER.getValue().shortValue());
        }
        employee.setPositionId(positionId);
        employee.setPositionName(positionName);
        employee.setCardNo(cardNo);
        employee.setMobile(mobile);
        employee.setEnterDate(enterDate);

        employee.setJobNo(jobNo);
        employee.setStatus(true);
        employee.setCreateBy(userDto.getName());
        employee.setUpdateBy(userDto.getName());
        employeeMapper.insert(employee);
    }

    /**
     * 根据学校ID查询园长列表
     * @param params 学校ID
     * @return 园长信息列表
     */
    @Override
    public List<EmployeeInfoDto> getMasterEmployeeList(Map<String,Object> params){
        return employeeMapper.getSchoolMasterInfo(params);
    }

    @Override
    public EmployeeInfoDto getClassMasterInfo(Long orgId, Long classId){
        Map<String, Object> params = new HashMap<>(4);
        params.put("orgId", orgId);
        params.put("classId", classId);

        ClassInfo classInfo = classInfoMapper.getByPrimaryKey(classId);

        EmployeeInfoDto employeeInfoDto = new EmployeeInfoDto();

        if(null!=classInfo&&null!=classInfo.getMasterId()){

            params.put("userId", classInfo.getMasterId());
            Employee employee = employeeMapper.getByMapParams(params);

            if(null!=employee){
                BeanUtils.copyProperties(employee, employeeInfoDto);

            }
        }
        return employeeInfoDto;
    }

    @Override
    public  List<Long> getEmployeeListAll(){
        return employeeMapper.getEmployeeListAll();
    }

    @Override
    public List<Employee> getMasterByUserIds(List<Long> userIds){
        HashMap<String, Object> param = new HashMap<>();
        param.put("userIds",userIds);
        return employeeMapper.getMasterByUserIds(param);
    }

    @Override
    public  List<Employee> getFamilyListByUpdateTime(Long orgId, Date date){
        HashMap<String, Object> param = new HashMap<>();
        param.put("orgId",orgId);
        param.put("updateTime",date);
        return employeeMapper.getFamilyListByUpdateTime(param);
    }
}
